package api

import (
	"context"
	"fmt"
	"net/http"
	"strings"
	"todolist/pkg/auth"
)

func NewRouter(h *Handler) http.Handler {
	mux := http.NewServeMux()
	
	mux.HandleFunc("/register", h.Register)
	mux.HandleFunc("/login", h.Login)
	mux.HandleFunc("/tasks", h.HandleTasks)
	
	return mux
}

func (h *Handler) HandleTasks(w http.ResponseWriter, r *http.Request) {
	// 验证 token
	userID, err := validateToken(r)
	if err != nil {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}

	// 将 userID 添加到上下文
	ctx := context.WithValue(r.Context(), "userID", userID)
	r = r.WithContext(ctx)

	switch r.Method {
	case "GET":
		h.GetTasks(w, r)
	case "POST":
		h.CreateTask(w, r)
	default:
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
	}
}

func validateToken(r *http.Request) (int, error) {
	authHeader := r.Header.Get("Authorization")
	if authHeader == "" {
		return 0, fmt.Errorf("no token provided")
	}

	// Bearer token格式
	parts := strings.Split(authHeader, " ")
	if len(parts) != 2 || parts[0] != "Bearer" {
		return 0, fmt.Errorf("invalid token format")
	}

	return auth.ValidateToken(parts[1])
} 